//
//  ARDevice.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/3/24.
//

import Foundation
import UIKit

import AdSupport
import AppTrackingTransparency

class ARDevice {
    
    /// 状态 - 只有 iOS14之后才需要请求，其他情况不需要
    /// 如果用户拒绝，则直接获取 idfv / 自己生成
    enum uuidRequestStatus: Equatable {
        case notDetermined
        case requesting
        case authorized(String)
        
        var idfa: String? {
            switch self {
            case .authorized(let idfa):
                return idfa
            default:
                return nil
            }
        }
    }
    
    // 请求状态
    private var _status: uuidRequestStatus {
        didSet {
            if let idfa = _status.idfa {
                self._saveIdfa(idfa)
            }
        }
    }
    var uuidResult: uuidRequestStatus {
        get {
            return _status
        }
    }
    
    /// 设备型号
    let phoneModel: String
    
    static let uuidUpdateNotification: Notification.Name = Notification.Name(rawValue: "ARDevice.uuidUpdateNotification")
    private static let uuidKey = "AquaRaft.uuidkey"
    
    // 单例
    
    static let share = ARDevice()
    
    private init() {
        self._status = .notDetermined
        
        // 设备型号
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        self.phoneModel = identifier
        
        self.configManager()
    }
    
    private func configManager() {
        // 获取userdefault
        let uuid = UserDefaults.standard.string(forKey: Self.uuidKey)
        if let uuid = uuid {
            self._status = .authorized(uuid)
            
            // 发送通知
            NotificationCenter.default.post(name: Self.uuidUpdateNotification, object: nil)
        }
    }
    
    // MARK: - Idfa
    
    func requestIdfa() {
        
        if _status != .notDetermined {
            // 请求中
            return
        }
        _status = .requesting
        
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { status in
                switch status {
                case .authorized:
                    let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                    if self._checkidfa(idfa) {
                        self._status = .authorized(idfa)
                    } else {
                        self._requestIdfv()
                    }
                default:
                    self._requestIdfv()
                }
            }
            return
        }
        
        // 其他情况可以直接获取
        let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
        if self._checkidfa(idfa) {
            self._status = .authorized(idfa)
        } else {
            self._requestIdfv()
        }
    }
    
    private func _requestIdfv() {
        let idfv = UIDevice.current.identifierForVendor?.uuidString
        if self._checkidfa(idfv ?? "") {
            self._status = .authorized(idfv ?? "")
        } else {
            // 生成一个UUID
            self._status = .authorized(NSUUID().uuidString)
        }
    }
    
    private func _checkidfa(_ idfa: String) -> Bool {
        if idfa.isEmpty {
            return false
        }
        
        if idfa == "00000000-0000-0000-0000-000000000000" {
            return false
        }
        return true
    }
    
    private func _saveIdfa(_ idfa: String) {
        UserDefaults.standard.set(idfa, forKey: Self.uuidKey)
        UserDefaults.standard.synchronize()
    }
    
}
